const fs = require('fs');
const path = require('path');

function mergeAndFixDtsFiles(moduleType) {
  const typesDir = path.join(__dirname, '..', 'src', 'types');
  const libDir = path.join(typesDir, 'lib');
  const modulesDir = path.join(typesDir, 'modules');
  const baseDir = path.join(typesDir, 'base');
  const irtcDir = path.join(__dirname, '..', 'src', 'lib');

  // 读取所有需要的 .d.ts 文件
  const files = [
    path.join(irtcDir, 'irtc.d.ts'),
    path.join(modulesDir, 'snapshot.d.ts'),
    path.join(baseDir, 'network.d.ts'),
    path.join(baseDir, 'navigator.d.ts'),
    path.join(libDir, 'ams_client.d.ts'),
    path.join(libDir, 'irtcScript.d.ts'),
    path.join(libDir, 'ccs_client.d.ts'),
    path.join(libDir, 'imUpgrade.d.ts'),
    path.join(libDir, 'whiteboard.d.ts'),
    path.join(libDir, 'deviceTool.d.ts'),
    path.join(baseDir, 'error.d.ts'),
    path.join(modulesDir, 'map_location.d.ts'),
  ];
  let ivcs = '';
  if (moduleType === 'agent') {
    files.push(path.join(libDir, 'AgentModule.d.ts'));
    ivcs = `
export interface IVCSProps {
    agent: Agent;
    IRtc: any;
}
`;
  }
  if (moduleType === 'mini') {
    files.push(path.join(libDir, 'irtcMiniScript.d.ts'));
    files.push(path.join(libDir, 'clientMini.d.ts'));
    ivcs = `
export interface IVCSProps {
    customer: Customer;
}
`;
  }
  if (moduleType === 'server') {
    files.push(path.join(libDir, 'ivcsAgent.d.ts'));
    ivcs = `
export interface IVCSProps {
    agent: agent;
}
`;
  }
  if (moduleType === 'customer') {
    files.push(path.join(libDir, 'ClientModule.d.ts'));
    ivcs = `
export interface IVCSProps {
    client: Client;
    IRtc: any;
}
`;
  }
 

  let mergedContent = ivcs + `
declare var ivcs: IVCSProps;
`;

  files.forEach(file => {
    if (fs.existsSync(file)) {
      let content = fs.readFileSync(file, 'utf8');
      // 移除 export 语句和 import 语句
    //   content = content.replace(/export /g, '');
      content = content.replace(/import [^;]+;/g, '');
      // remove extends EventEmitter<[never]>
      content = content.replace(/extends EventEmitter<[^\n]+>/g, '');
      mergedContent += content + '\n\n';
    } else {
      console.warn(`Warning: File not found: ${file}`);
    }
  });

  mergedContent += `
`;

  // 写入合并后的文件
  const finalDir = path.join(__dirname, '..', 'dist', moduleType);
  if (!fs.existsSync(finalDir)) {
    fs.mkdirSync(finalDir, { recursive: true });
  }
  fs.writeFileSync(path.join(finalDir, 'ivcs.d.ts'), mergedContent);
}

const moduleType = process.argv[2];
mergeAndFixDtsFiles(moduleType);